package org.lex.checksum.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.lex.checksum.utils.FinishListener;

public class AlgorithmRunner implements Runnable {
	private Algorithm alrorithm = null;
	private long processedByteCount = 0L;
	private byte[] buffer = null;
	private String result = "";
	private long fileTotalLength = 1L;
	// =======================
	private FinishListener finishListener = null;
	private File file = null;

	public AlgorithmRunner() {
		this.buffer = new byte[1024 * 1024 * 4];// 1 MB
	}

	public void setAlgorithm(Algorithm algorithm) {
		this.alrorithm = algorithm;
	}

	public void setFinishListener(FinishListener listener) {
		this.finishListener = listener;
	}

	public File getFile() {
		return this.file;
	}

	public void setFile(File file) {
		this.file = file;
		this.fileTotalLength = file.length();
		this.processedByteCount = 0L;
	}

	public long getProgress() {
		return processedByteCount;
	}

	public long getLength() {
		return this.fileTotalLength;
	}

	public String getResult() {
		return this.result;
	}

	public void run() {
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			long start = System.currentTimeMillis();
			this.alrorithm.reset();
			this.result = "";
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				this.alrorithm.update(buffer, 0, len);
				processedByteCount += len;
			}
			this.result = this.alrorithm.finish();
			this.fireFinished();
			System.out.println("using " + (System.currentTimeMillis() - start) + " ms");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void fireFinished() {
		if (null != this.finishListener) {
			this.finishListener.finished();
		}
	}
}
